﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace xx
{
	/// <summary>
    /// 巡逻
    /// </summary>
	public class CoroutineExample02 : MonoBehaviour {
        public Transform[] wayPoints;
        private float moveSpeed = 1;

        private IEnumerator Pathfinding()
        {
            for (int i = 0; i < wayPoints.Length; i++)
            {
                //transform.LookAt(wayPoints[i].position);
                //暂时退出，待移动到目标点时继续循环
                yield return StartCoroutine(MoveToTarget(wayPoints[i].position));
                //等价于yield return MoveToTarget(wayPoints[i].position);//省略的写法
            }

        }
        private IEnumerator MoveToTarget(Vector3 pos)
        {
            transform.LookAt(pos);//转向目标点或者放到Pathfinding方法的for循环中;也可以再写一个协程
            //transform.position = Vector3.Lerp(transform.position, pos, Time.deltaTime * moveSpeed);//由慢到快运动
            while (Vector3.Distance(transform.position,pos) > 0.1f)
            {
                transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * moveSpeed);//匀速运动
                //暂时退出，等待下一帧继续循环
                yield return null;//相当于yield return new WaitForFixedUpdate();
            }
        }
        //**********测试代码**********
        private void OnGUI()
        {
            if (GUILayout.Button("开始巡逻"))
            {
                StartCoroutine(Pathfinding());
            }

        }
        
    }
}

